<template>
  <div class="store-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form">
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入门店名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="searchForm.province" placeholder="请选择省份" clearable @change="handleProvinceChange">
            <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="searchForm.city" placeholder="请选择城市" clearable :disabled="!searchForm.province">
            <el-option v-for="item in cityOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增门店</el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="门店名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="code" label="门店编号" width="120" align="center"></el-table-column>
        <el-table-column prop="province" label="省份" width="100"></el-table-column>
        <el-table-column prop="city" label="城市" width="100"></el-table-column>
        <el-table-column prop="district" label="区县" width="100"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120" align="center"></el-table-column>
        <el-table-column prop="businessHours" label="营业时间" width="150" align="center"></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="门店图片" width="100" align="center">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.image"
              style="width: 60px; height: 40px"
              :src="scope.row.image" 
              :preview-src-list="[scope.row.image]">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" align="center"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="info" icon="el-icon-location" @click="handleViewMap(scope.row)">查看地图</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" @close="resetForm('form')">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入门店名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入门店编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" placeholder="请选择省份" @change="handleFormProvinceChange">
                <el-option v-for="item in provinceOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-select v-model="form.city" placeholder="请选择城市" :disabled="!form.province">
                <el-option v-for="item in formCityOptions" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区县" prop="district">
              <el-input v-model="form.district" placeholder="请输入区县"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="营业时间" prop="businessHours">
              <el-input v-model="form.businessHours" placeholder="例如：9:00-18:00"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="门店图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="门店描述" prop="description">
          <el-input type="textarea" v-model="form.description" :rows="3" placeholder="请输入门店描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 地图对话框 -->
    <el-dialog title="门店位置" :visible.sync="mapDialogVisible" width="800px">
      <div id="map-container" style="width: 100%; height: 500px;"></div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
// 中国省市数据
import { provinces, cities } from '@/utils/area'

export default {
  name: 'StoreList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        province: '',
        city: '',
        status: ''
      },
      // 分页参数
      pageParams: {
        current: 1,
        size: 10
      },
      // 表格数据
      tableData: [],
      total: 0,
      loading: false,
      selectedIds: [],
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增门店',
      mapDialogVisible: false,
      // 表单数据
      form: {
        id: null,
        name: '',
        code: '',
        address: '',
        province: '',
        city: '',
        district: '',
        longitude: '',
        latitude: '',
        phone: '',
        businessHours: '',
        image: '',
        description: '',
        status: 1
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入门店编号', trigger: 'blur' }],
        province: [{ required: true, message: '请选择省份', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-\d{7,8}$/, message: '请输入正确的电话格式', trigger: 'blur' }
        ]
      },
      // 选项数据
      provinceOptions: provinces,
      cityOptions: [],
      formCityOptions: [],
      statusOptions: [
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ],
      // 地图对象
      map: null,
      marker: null
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取门店列表数据
    fetchData() {
      this.loading = true
      const params = {
        current: this.pageParams.current,
        size: this.pageParams.size,
        ...this.searchForm
      }
      
      request({
        url: '/car-vehicle/stores/page',
        method: 'get',
        params
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 处理省份变更
    handleProvinceChange(province) {
      this.searchForm.city = ''
      if (province) {
        this.cityOptions = cities[province] || []
      } else {
        this.cityOptions = []
      }
    },
    // 处理表单省份变更
    handleFormProvinceChange(province) {
      this.form.city = ''
      if (province) {
        this.formCityOptions = cities[province] || []
      } else {
        this.formCityOptions = []
      }
    },
    // 处理搜索
    handleSearch() {
      this.pageParams.current = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.cityOptions = []
      this.handleSearch()
    },
    // 处理选择变更
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    // 处理页码变更
    handleCurrentChange(current) {
      this.pageParams.current = current
      this.fetchData()
    },
    // 处理每页数量变更
    handleSizeChange(size) {
      this.pageParams.size = size
      this.pageParams.current = 1
      this.fetchData()
    },
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增门店'
      this.form = {
        id: null,
        name: '',
        code: '',
        address: '',
        province: '',
        city: '',
        district: '',
        longitude: '',
        latitude: '',
        phone: '',
        businessHours: '',
        image: '',
        description: '',
        status: 1
      }
      this.formCityOptions = []
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑门店'
      this.form = { ...row }
      // 设置城市选项
      if (row.province) {
        this.formCityOptions = cities[row.province] || []
      }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm('确认删除该门店?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/car-vehicle/stores/${row.id}`,
          method: 'delete'
        }).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    // 处理批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的门店')
        return
      }
      this.$confirm(`确认删除选中的${this.selectedIds.length}个门店?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: '/car-vehicle/stores/batch',
          method: 'delete',
          data: this.selectedIds
        }).then(() => {
          this.$message.success('批量删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    // 处理状态变更
    handleStatusChange(row) {
      request({
        url: `/car-vehicle/stores/${row.id}/status/${row.status}`,
        method: 'put'
      }).then(() => {
        this.$message.success('状态修改成功')
      })
    },
    // 查看地图
    handleViewMap(row) {
      if (!row.longitude || !row.latitude) {
        this.$message.warning('该门店未设置经纬度坐标')
        return
      }
      
      this.mapDialogVisible = true
      // 使用setTimeout确保DOM已经渲染
      setTimeout(() => {
        // 这里需要引入地图API，如高德地图或百度地图
        // 以下为示例代码，实际使用时需要替换为真实的地图API
        this.$message.info('地图功能需要接入第三方地图API，这里仅作为示例')
      }, 300)
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            url: '/car-vehicle/stores/save',
            method: 'post',
            data: this.form
          }).then(() => {
            this.$message.success(`${this.form.id ? '更新' : '添加'}成功`)
            this.dialogVisible = false
            this.fetchData()
          })
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.form.image = res.data.url;
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败：' + res.message);
      }
    },
    // 图片上传前处理
    beforeImageUpload(file) {
      const isImage = file.type.indexOf('image/') === 0
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 自定义上传处理
    customUpload(event) {
      const file = event.file
      const formData = new FormData()
      formData.append('file', file)

      request({
        url: '/car-integration/files/upload',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        console.log('上传响应数据:', res);
        if (res.code === 200) {
          this.handleImageSuccess(res, file);
        } else {
          this.$message.error('上传失败：' + res.message);
        }
      }).catch(err => {
        console.error('上传错误:', err);
        this.$message.error('上传失败');
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.store-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: flex-start;
      
      .el-button {
        margin-right: 10px;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 100px;
    
    &:hover {
      border-color: #409EFF;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    
    .avatar {
      width: 178px;
      height: 100px;
      display: block;
      object-fit: cover;
    }
  }
}
</style> 